package com.xiaozhuai.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaozhuai.pojo.User;
import com.xiaozhuai.pojo.Users;
import com.xiaozhuai.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {

    @ResponseBody
    @RequestMapping(value = "/json/01",produces = "application/json;charset=utf-8")
    public String json01() throws JsonProcessingException {
        //Jackson,ObjectMapper
        User user = new User("小拽",16,"男");
        ObjectMapper mapper = new ObjectMapper();
        String str = mapper.writeValueAsString(user);
        return str;
    }

    @ResponseBody
    @RequestMapping(value = "/json/02",produces = "application/json;charset=utf-8")
    public String json02() throws JsonProcessingException {
        User user1 = new User("小拽1",16,"男");
        User user2 = new User("小拽2",17,"男");
        User user3 = new User("小拽3",18,"男");
        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        return JsonUtils.getJson(userList);
    }

    @ResponseBody
    @RequestMapping(value = "/json/03",produces = "application/json;charset=utf-8")
    public String json03() throws JsonProcessingException {
        Date date= new Date();
        //使用Java自带的格式化工厂来格式化时间
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");
        //String format = sdf.format(date);

        String str = JsonUtils.getJson(date,"yyyy-MM-dd HH:hh:ss");
        return str;
    }

    @ResponseBody
    @RequestMapping(value = "/json/04",produces = "application/json;charset=utf-8")
    public String json04() throws JsonProcessingException {
        List<User> userList = new ArrayList<User>();
        User user1 = new User("小拽1",16,"男");
        User user2 = new User("小拽2",17,"男");
        User user3 = new User("小拽3",18,"男");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        String jsonString = JSON.toJSONString(userList);
        return jsonString;
    }

    @ResponseBody
    @RequestMapping(value = "/json/05",produces = "application/json;charset=utf-8")
    public String json05(@RequestBody Users users) throws JsonProcessingException {

        String jsonString = JSON.toJSONString(users);
        return jsonString;
    }
}
